package io.github.wppli.domain.pay.service;

import cc.jq1024.middleware.redisson.IRedissonService;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import io.github.wppli.domain.pay.event.OrderBehaviorsEvent;
import io.github.wppli.domain.pay.model.aggregates.CreateOrderAggregate;
import io.github.wppli.domain.pay.model.entity.OrderEntity;
import io.github.wppli.domain.pay.model.entity.PayOrderEntity;
import io.github.wppli.domain.pay.model.entity.ProductEntity;
import io.github.wppli.domain.pay.model.valobj.OrderStatusVO;
import io.github.wppli.domain.pay.model.valobj.PayStatusVO;
import io.github.wppli.domain.pay.model.valobj.PayTypeVO;
import io.github.wppli.domain.pay.repository.IOrderRepository;
import io.github.wppli.domain.pay.util.PaySignUtil;
import io.github.wppli.domain.recommond.repository.IProductRepository;
import io.github.wppli.types.snow.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author li--jiaqiang 2025−03−19
 */
@Slf4j
@Service
public class OrderService extends AbstractOrderService {
    private final IRedissonService redissonService;

    public OrderService(SnowflakeIdGenerator snowflakeIdGenerator, IOrderRepository orderRepository, IProductRepository productRepository, OrderBehaviorsEvent orderBehaviorsEvent, IRedissonService redissonService) {
        super(snowflakeIdGenerator, orderRepository, productRepository, orderBehaviorsEvent);
        this.redissonService = redissonService;
    }

    @Value("${personal.wxpay.appid}")
    private String appid;
    @Value("${personal.wxpay.mchid}")
    private String mchid;
    @Value("${personal.wxpay.mchId}")
    private String personalMchId;
    @Value("${personal.wxpay.key}")
    private String personalKey;
    @Value("${personal.wxpay.notifyUrl}")
    private String personalNotifyUrl;
    @Value("${personal.wxpay.url}")
    private String personalUrl;


    @Override
    protected OrderEntity doSaveOrder(Long userId, ProductEntity productEntity) {
        OrderEntity orderEntity = new OrderEntity();
        // 雪花算法生成id
        orderEntity.setOrderId(String.valueOf(snowflakeIdGenerator.nextId()));
        orderEntity.setOrderTime(LocalDateTime.now()); // 下单时间
        orderEntity.setOrderStatus(OrderStatusVO.CREATE); // 订单状态: 创建完成
        orderEntity.setTotalAmount(productEntity.getPrice()); // 商品价格(订单金额)
        orderEntity.setPayTypeVO(PayTypeVO.WEIXIN_NATIVE); // 支付方式 -> 微信支付
        // 聚合信息(用户 + 商品 + 订单)
        CreateOrderAggregate aggregate = CreateOrderAggregate
                .builder()
                .userId(userId)
                .product(productEntity)
                .order(orderEntity)
                .build();
        // 保存订单；订单和支付，是2个操作。
        // 一个是数据库操作，一个是HTTP操作。所以不能一个事务处理，只能先保存订单再操作创建支付单，如果失败则需要任务补偿
        orderRepository.saveOrder(aggregate);
        return orderEntity;
    }

    /**
     * 蓝兔个人微信支付 - 生成微信支付单
     * @param userId 用户id
     * @param orderId 订单id
     * @param productName 产品名
     * @param amountTotal 金额
     * @return 支付单实体
     */
    @Override
    protected PayOrderEntity doPersonalPrepayOrder(Long userId, String orderId, String productName, String amountTotal) {
        //当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

        Map<String, Object> map = new HashMap<>();
        map.put("mch_id", personalMchId);
        map.put("out_trade_no", orderId);
        map.put("total_fee", amountTotal);
        map.put("body", productName);
        map.put("notify_url", personalNotifyUrl);
        map.put("timestamp", timestamp);
        String sign = PaySignUtil.createSign(map, personalKey);
        map.put("sign", sign);
        String result = HttpRequest.post(personalUrl)
                .form(map)
                .execute()
                .body();
        String msg = "";
        if (StrUtil.isBlank(result)) {
            msg = "API接口返回为空，请联系客服";
        } else {
            try {
                JSONObject jsonObject = (JSONObject)JSONObject.parse(result);
                Integer code = jsonObject.getInteger("code");
                if(code == 0){
                    String qrcode = jsonObject.getJSONObject("data").getString("QRcode_url");
                    msg = "请使用微信扫码下方二维码:" + qrcode;
                    // 构造支付实体
                    PayOrderEntity payOrderEntity = PayOrderEntity.builder()
                            .userId(userId)
                            .orderId(orderId)
                            .payUrl(qrcode)
                            .payStatus(PayStatusVO.WAIT) // 等待支付
                            .build();
                    // 更新订单支付信息
                    orderRepository.updateOrderPayInfo(payOrderEntity);
                    return payOrderEntity;
                } else {
                    String msgStr = jsonObject.getString("msg");
                    msg = "返回失败：" + msgStr;
                }
            } catch (Exception e) {
                log.error("生成支付单出错: ", e);
            }
        }
        log.info(msg);
        return null;
    }

    @Override
    public boolean changeOrderPaySuccess(String orderId, String transactionId, BigDecimal totalAmount, Date payTime) {
        return orderRepository.changeOrderPaySuccess(orderId, transactionId, totalAmount, payTime);
    }

    @Override
    public CreateOrderAggregate queryOrder(String orderId) {
        return orderRepository.queryOrder(orderId);
    }

    /**
     * 查询待补货订单
     */
    @Override
    public List<String> queryReplenishmentOrder() {
        return orderRepository.queryReplenishmentOrder();
    }

    @Override
    public List<String> queryNoPayNotifyOrder() {
        return orderRepository.queryNoPayNotifyOrder();
    }

    /**
     * 查询超时15分钟，未支付订单
     */
    @Override
    public List<String> queryTimeoutCloseOrderList() {
        return orderRepository.queryTimeoutCloseOrderList();
    }

    /**
     * 变更；订单支付关闭
     */
    @Override
    public boolean changeOrderClose(String orderId) {
        return orderRepository.changeOrderClose(orderId);
    }

    @Override
    public List<ProductEntity> queryProductList() {
        return orderRepository.queryProductList();
    }

    @Override
    public void saveProductSku(ProductEntity productEntity) {
        orderRepository.saveProductSku(productEntity);
    }

    @Override
    public void createViewOrder(String userId, Long productId) {
        String limitKey = "product_view_limit_" + userId;
        if (redissonService.isExists(limitKey)) {
            return;
        }
        // 10 分钟防止重复提交
        redissonService.setValue(limitKey, 1, 10, TimeUnit.MINUTES);

        String key = "product_view_count_" + productId;
        redissonService.incr(key);

        orderRepository.createViewOrder(productId);
    }

    @Override
    public void createBuyOrder(Long productId, Integer count)  {
        String key = "product_buy_count_" + productId;
        redissonService.incrBy(key, count);

        orderRepository.createBuyOrder(productId, count);
    }
}